var Dashboard = angular.module('dashboard',['$strap.directives','textAngular','ngSanitize','ngResource']);
Dashboard.factory('UserService', function() {
	return {
		authorTaskMe : (currentUser.length != 0) ? true : false
	};
	
});

Dashboard.directive('bindHtmlUnsafe', function( $parse, $compile ) {
    return function( $scope, $element, $attrs ) {
        var compile = function( newHTML ) {
            newHTML = $compile(newHTML)($scope);
            $element.html('').append(newHTML);        
        };
        
        var htmlName = $attrs.bindHtmlUnsafe;
        
        $scope.$watch(htmlName, function( newHTML ) {
            if(!newHTML) return;
            compile(newHTML);
        });
   
    };
});
Dashboard.directive('ngHtml', function() {
	return function(scope, element, attrs) {
		
		scope.$watch(attrs.ngHtml, function(value) {
			
			element[0].innerHTML = value;
		});
	}
});

Dashboard.directive('ngRightClick', function($parse) {
    return function(scope, element, attrs) {
        var fn = $parse(attrs.ngRightClick);
        element.bind('contextmenu', function(event) {
            scope.$apply(function() {
                event.preventDefault();
                fn(scope, {$event:event});
            });
        });
    };
});
Dashboard.controller('CmsController', function($scope,$http) {
});

Dashboard.controller('DashBoardController', function($scope,$http,$modal,UserService,$timeout) {
	var s = $scope;
	// $scope.myHTML = 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
	s.modalCreateProject = function(){
		modalCreateProject();
	}
	s.removeProject = function(array,index,_this){
		jConfirm('Are you sure you want to permanently remove this project?', 'Delete project', function(r) {
			if(r){
				
				modelsProjects.remove($(".class_remove_project"+index).attr("uuid"));
				$scope.$apply(function() {
					array.splice(index, 1);
					
					
				});
				
			}else{
			
			}
		});
	}
	/**
	 * Menu left
	 */
	$scope.toggleTab = function(toggle) {
		if(toggle==0){
			$scope.activeTab1 = "active";
			$scope.activeTab2 = "";
		}else{
			$scope.activeTab1 = "";
			$scope.activeTab2 = "active";
		}
	};
	
	
	
	s.toggleTab(0);
	$scope.tabprojects = function(){
		s.toggleTab(0);
	}
	
	
	$scope.tabdatabases = function(){
		s.toggleTab(1);
	}
	

	/**
	 * Menu User
	 */
	
	$scope.authorTaskMe = UserService.authorTaskMe;
	$scope.avatarHeader = false;
	$scope.linkAvatar = "/upload/user/default/no-photo.png";
	if($scope.authorTaskMe && currentUser.avatar.status){
		$scope.avatarHeader = true;
		$scope.linkAvatar = currentUser.avatar.link;
	}else{
		
		$scope.avatarHeader = false;
		
	}
	$scope.fullname = "";

	if($scope.authorTaskMe){
		$scope.fullname = currentUser.user.first_name+" "+currentUser.user.last_name;

	}
	
	var t  = $(".dropdown-wrapper").width()+20;
	$scope.wdropdownUser = t+"px";
	
	
	
	
	
	
	reloadPage();
	
	$scope.projects = projects;
    // $scope.getProjects();
	
	$scope.newProject = function(){

		$.post("/api/projects/save",{"name":modelsProjects.name})
		.success(function(data, status, headers, config) {
			
			if(data.error){
				showStickyErrorToast(data.message);
			}else{
				$scope.$apply(function() {
					projects.push(data.data);
					
					reloadPage();
					
					
				});
				showStickySuccessToast(data.message);
				

				caseProject.renderItemProject(data.data);
				
			}
		}).error(function(data, status, headers, config) {
			if(status=="error") showStickyErrorToast(data.responseText);
			console.log(data);
			console.log(status);
		});
	}
	$scope.viewSource =function(){
		// window.location="view-source:" + window.location.origin+""+currentProject.urlIframe;
	}
	
	$scope.applyMode =function(){
		$.get("/api/public/applyMode",{"name":curFile})
		.success(function(data, status, headers, config) {
			console.log(data);
			if(data.error){
				showStickyErrorToast(data.message);
			}else{
				caseProject.viewFileIframe(curFile);
				
			}
		}).error(function(data, status, headers, config) {
			if(status=="error") showStickyErrorToast(data.responseText);
			console.log(data);
			console.log(status);
		});
	}
	$scope.public =function(){
		var url = window.location.origin+"/projects/source/"+currentUser.user.id+"/"+currentProject.name;
		var win=window.open(url, '_blank');
		win.focus();
		
		// caseProject.toggleLoading(true);
		
		// caseProject.openBoardPublic();
		
		
		// currentProject.urlIframe = url;
		// $(".cms-public").html("<iframe id='project_frame' src='"+currentProject.urlIframe+"' width='100%' height='100%'></iframe>");
		// try{
			// ptCms.init();
		// }catch(e){
			// console.log("Error Iframe: "+e.message());
		// }
		
		// caseProject.toggleLoading(false);
		
	}
	$scope.board =function(){
		
	}

	
});

function reloadPage(){
	$('.loading-project').hide();
	$(".cms-board").html('');
	if(projects.length == 0){
		$('.no-project').show();
	}else{
		$('.no-project').hide();
		
	}
	
}

$().ready(function(e){
	$(".linkAvatar").live('click',function(e){
		toogleDropdownUser();
	});
	$( document ).on( "click", function( event ) {
		var dropdownUser = $(event.target).attr('dropdown');
		if(typeof dropdownUser == "undefined"){
			$(".dropdownUser").addClass("hidden");
		}
	});
});
function modalCreateProject(){
	jPrompt('Type project name', '', 'Create a project', function(r) {
		if( r ){
			if(r==""){
				
			}else{
				modelsProjects.name = r;
				$("#add-project").trigger("click");
			}
		}
	});
}
function toogleDropdownUser(){
	if($(".dropdownUser").hasClass('hidden')){
		$(".dropdownUser").removeClass("hidden");
	}else{
		$(".dropdownUser").addClass("hidden");
	}
}

$(function(){

	/**
	 * Live click on the file
	 **/
	$("ul.dirproject li a").live("click",function(e){
		var tmp = $(this).html().split(".");
		var ext = tmp[tmp.length-1];
		
		switch(ext){
			case "html":
				curFile = $(this).html();
				caseProject.viewFileIframe($(this).html());
			break;
			default:
				caseProject.fileNotOpen(ext);
			break;
		}
	});
	
    /*$.contextMenu({
        selector: '.css-treeview', 
        callback: function(key, options) {
            var m = "clicked: " + key;
            window.console && console.log(m) || alert(m); 
        },
        items: {
            // "edit": {name: "Edit", icon: "edit"},
            // "cut": {name: "Cut", icon: "cut"},
            // "copy": {name: "Copy", icon: "copy"},
            // "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            // "sep1": "---------",
            // "quit": {name: "Quit", icon: "quit"}
        }
    });
    
    $('.css-treeview').on('click', function(e){
        console.log('clicked', this);
    });*/
});